package com.tools.utils;

import com.tools.pojo.workflow.po.FlowInstance;
import com.tools.service.workflow.FlowInstanceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class DataFixTool implements CommandLineRunner {

    private final FlowInstanceService flowInstanceService;

    @Override
    public void run(String... args) throws Exception {
        fixExecutionPathData();
    }

    /**
     * 修复执行路径数据
     */
    public void fixExecutionPathData() {
        try {
            log.info("开始检查执行路径数据...");

            List<FlowInstance> instances = flowInstanceService.list();
            int fixedCount = 0;

            for (FlowInstance instance : instances) {
                if (instance.getExecutionPath() != null &&
                        instance.getExecutionPath().contains("\"completed\"")) {

                    try {
                        // 重新解析和序列化执行路径，这会自动移除未知字段
                        var executionPath = flowInstanceService.parseExecutionPath(instance.getExecutionPath());
                        String fixedJson = flowInstanceService.serializeExecutionPath(executionPath);

                        if (!fixedJson.equals(instance.getExecutionPath())) {
                            instance.setExecutionPath(fixedJson);
                            flowInstanceService.updateById(instance);
                            fixedCount++;
                            log.debug("修复流程实例执行路径: {}", instance.getId());
                        }
                    } catch (Exception e) {
                        log.warn("修复流程实例执行路径失败: {}", instance.getId(), e);
                    }
                }
            }

            log.info("执行路径数据修复完成，共修复 {} 条记录", fixedCount);

        } catch (Exception e) {
            log.error("执行路径数据修复失败", e);
        }
    }


}
